import 'dart:math';

import 'package:auto_size_text/auto_size_text.dart';
import 'package:flutter/material.dart';
import 'package:furaha_mkopo/commonTool/fm_jump_tool.dart';
import 'package:furaha_mkopo/commonTool/fm_language_tool.dart';
import 'package:furaha_mkopo/commonTool/fm_route_tool.dart';
import 'package:furaha_mkopo/commonUI/fm_progress_hud.dart';
import 'package:furaha_mkopo/commonUI/fm_toast.dart';
import 'package:furaha_mkopo/manager/fm_global_manager.dart';
import 'package:furaha_mkopo/page/base/fm_base_page_widget.dart';
import 'package:furaha_mkopo/page/home/api/fm_home_click_access_api.dart';
import 'package:furaha_mkopo/page/home/controller/fm_home_big_controller.dart';
import 'package:furaha_mkopo/page/home/dialog/fm_auth_completed_dialog.dart';
import 'package:furaha_mkopo/page/home/entity/fm_home_click_access_entity.dart';
import 'package:furaha_mkopo/page/home/entity/fm_home_entity.dart';
import 'package:furaha_mkopo/page/login/fm_login_page.dart';
import 'package:geolocator_platform_interface/src/models/position.dart';
import 'package:get/get.dart';

class FMHomeSmallCardSlotPage extends FMBasePageWidget {
  FMHomeEntity fmHomeEntity;
  FMHomeVoiceEntity? topEntity;
  List<FMHomeVoiceEntity>? beamedEntities;

  FMHomeSmallCardSlotPage({super.key, required this.fmHomeEntity}) {
    for (int i = 0; i < (fmHomeEntity.beamed?.length ?? 0); i++) {
      FMHomeBeamedEntity beamedEntity = fmHomeEntity.beamed![i];
      if (beamedEntity.firm == "that" &&
          beamedEntity.voice?.isNotEmpty == true) {
        topEntity = beamedEntity.voice!.first;
        continue;
      }
      if (beamedEntity.firm == "was") {
        beamedEntities = beamedEntity.voice ?? [];
      }
    }
  }

  @override
  State<FMHomeSmallCardSlotPage> createState() => _FMHomeSmallCardSlotPageState();
}

class _FMHomeSmallCardSlotPageState extends FMBasePageState<FMHomeSmallCardSlotPage> {
  final controller = Get.put(FMHomeBigController());

  @override
  Widget build(BuildContext context) {
    return Stack(
      fit: StackFit.expand,
      children: [
        generateBottomBg(),
        generateTopContentBg(),
        generateContent(context)
      ],
    );
  }

  Widget generateBottomBg() {
    return Positioned(
        bottom: -58,
        left: 0,
        right: 0,
        child: Image.asset(
          "assets/home/ic_small_bottom_bg.webp",
          fit: BoxFit.fill,
        ));
  }

  Widget generateTopContentBg() {
    return Positioned(
        top: 0,
        left: 0,
        right: 0,
        child: Image.asset(
          FMLanguageTool.getAssets("assets/home/ic_samll_top_centent_bg",suffix: ".webp"),
          fit: BoxFit.fill,
        ));
  }

  Widget generateContent(BuildContext context) {
    return Positioned.fill(
      left: 0,
      right: 0,
      top: 60 + offsetTop(context),
      child: Column(
        children: [
          generateTitle(),
          const SizedBox(
            height: 10,
          ),
          generateMoney(),
          const SizedBox(
            height: 10,
          ),
          generateLeftRightCard(),
          generateApplyButton(context),
          generateBottomContent()
        ],
      ),
    );
  }

  Widget generateTitle() {
    String title;
    if (widget.topEntity == null) {
      title = "";
    } else {
      title = widget.topEntity?.attempt ?? "";
    }
    return Text(
      title,
      style: const TextStyle(fontSize: 17, color: Colors.black),
    );
  }

  Widget generateMoney() {
    String money;
    if (widget.topEntity == null) {
      money = "";
    } else {
      money = widget.topEntity?.wheel ?? "";
    }
    const angle = (180 - 131) * (pi / 180);
    return Container(
      margin: const EdgeInsets.symmetric(horizontal: 27),
      child: ShaderMask(
        shaderCallback: (bounds) => LinearGradient(
          colors: const [Color(0xFFFF8400), Color(0xFFFFE100)],
          begin: Alignment(-cos(angle), sin(angle)), // 根据三角函数计算
          end: Alignment(cos(angle), -sin(angle)),
        ).createShader(bounds),
        blendMode: BlendMode.srcIn,
        child: AutoSizeText(
          money,
          maxLines: 1,
          maxFontSize: 60,
          minFontSize: 5,
          style: const TextStyle(
            fontSize: 60,
            fontWeight: FontWeight.bold, // 可保留其他样式
          ),
        ),
      ),
    );
  }

  Widget generateLeftRightCard() {
    String doors = "";
    String throne = "";
    String steps = "";
    String rarely = "";
    if (widget.topEntity != null) {
      doors = widget.topEntity?.doors ?? "--";
      throne = widget.topEntity?.throne ?? "";
      steps = widget.topEntity?.steps ?? "";
      rarely = widget.topEntity?.rarely ?? "";
    }
    return Container(
      margin: const EdgeInsets.symmetric(horizontal: 27),
      height: 72,
      decoration: const BoxDecoration(
        image: DecorationImage(
          image: AssetImage('assets/home/ic_big_card_bg.png'),
          fit: BoxFit.cover,
        ),
      ),
      child: Row(
        children: [
          Expanded(
              child: Row(
            children: [
              const SizedBox(
                width: 12,
              ),
              Image.asset(
                "assets/home/ic_big_left_bg.png",
                width: 41,
                height: 41,
              ),
              const SizedBox(
                width: 8,
              ),
              Column(
                mainAxisAlignment: MainAxisAlignment.center,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    doors,
                    style: const TextStyle(
                        fontSize: 15,
                        color: Colors.black,
                        fontWeight: FontWeight.bold),
                  ),
                  Text(
                    throne,
                    style: const TextStyle(fontSize: 12, color: Colors.black),
                  ),
                ],
              )
            ],
          )),
          Expanded(
              child: Row(
            children: [
              const SizedBox(
                width: 12,
              ),
              Image.asset(
                "assets/home/ic_big_right_bg.png",
                width: 41,
                height: 41,
              ),
              const SizedBox(
                width: 8,
              ),
              Column(
                mainAxisAlignment: MainAxisAlignment.center,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    steps,
                    style: const TextStyle(
                        fontSize: 15,
                        color: Colors.black,
                        fontWeight: FontWeight.bold),
                  ),
                  Text(
                    rarely,
                    style: const TextStyle(fontSize: 12, color: Colors.black),
                  ),
                ],
              )
            ],
          )),
        ],
      ),
    );
  }

  Widget generateApplyButton(BuildContext context) {
    String passing = "";
    if (widget.topEntity != null) {
      passing = widget.topEntity?.passing ?? "";
    }
    return GestureDetector(
      behavior: HitTestBehavior.translucent,
      onTap: () {
        controller.onRequestClickAccess(widget.topEntity?.useless.toString()??"", (tag, bidding, curListen){
          if(tag.isEmpty){
            controller.onRequestOught(authCompleted);
            return;
          }
          FMJumpTool.jumpAuth(context, tag, bidding, curListen, false);
        });
      },
      child: Container(
        height: 82,
        width: double.infinity,
        alignment: Alignment.center,
        decoration: const BoxDecoration(
          image: DecorationImage(
            image: AssetImage('assets/home/ic_big_btn_bg.png'),
            fit: BoxFit.fill,
          ),
        ),
        child: Container(
          padding: const EdgeInsets.only(top: 8),
          child: Text(
            passing,
            style: const TextStyle(
                fontSize: 20, color: Colors.white, fontWeight: FontWeight.bold),
          ),
        ),
      ),
    );
  }

  Widget generateBottomContent() {
    return Expanded(
      child: ListView.builder(
          itemCount: widget.beamedEntities?.length??0,
          padding: EdgeInsets.zero,
          physics: const AlwaysScrollableScrollPhysics(),
          shrinkWrap: true,
          itemBuilder: (context, index) {
            FMHomeVoiceEntity? voiceEntity = widget.beamedEntities?[index];
            return GestureDetector(
              behavior: HitTestBehavior.translucent,
              onTap: () {
                controller.onRequestClickAccess(voiceEntity?.useless.toString()??"", (tag, bidding, curListen){
                  if(tag.isEmpty){
                    controller.onRequestOught(authCompleted);
                    return;
                  }
                  FMJumpTool.jumpAuth(context, tag, bidding, curListen, false);
                });
              },
              child: Container(
                height: 131,
                width: double.infinity,
                margin:
                    const EdgeInsets.only(left: 16, right: 16, bottom: 8, top: 8),
                decoration: BoxDecoration(
                  borderRadius: const BorderRadius.all(Radius.circular(16)),
                  border: Border.all(color: const Color(0xFF5DFB18), width: 3),
                  color: const Color(0xFFF0FFED),
                ),
                child: Column(
                  children: [
                    const SizedBox(height: 10,),
                    Row(
                      children: [
                        const SizedBox(
                          width: 16,
                        ),
                        generateItemProfilePicture(voiceEntity?.felt),
                        const SizedBox(
                          width: 6,
                        ),
                        generateItemProfileName(voiceEntity?.attempt),
                        const Spacer(),
                        generateItemProfileBtn(context,voiceEntity?.passing,voiceEntity?.useless),
                        const SizedBox(
                          width: 16,
                        ),
                      ],
                    ),
                    const SizedBox(height: 8,),
                    Row(
                      children: [
                        const SizedBox(
                          width: 16,
                        ),
                        Expanded(child: generateItemMoney(voiceEntity?.wheel)),
                        Expanded(child: generateItemTip(voiceEntity?.requested)),
                        const SizedBox(
                          width: 16,
                        ),
                      ],
                    ),
                    const SizedBox(height: 8,),
                    Row(
                      children: [
                        const SizedBox(
                          width: 16,
                        ),
                        Expanded(child: generateItemBottomLeft(voiceEntity?.doors)),
                        Expanded(child: generateItemBottomRight(voiceEntity?.steps)),
                        const SizedBox(
                          width: 16,
                        )
                      ],
                    )
                  ],
                ),
              ),
            );
          }),
    );
  }

  Widget generateItemProfilePicture(String? src) {
    return Image.network(
      src??"",
      width: 32,
      height: 32,
      fit: BoxFit.cover,
      errorBuilder: (context,ob,stack){
        return Container(
          width: 32,
          height: 32,
          decoration: const BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.all(Radius.circular(16)),
          ),
        );
      },
    );
  }

  Widget generateItemProfileName(String? attempt) {
    return Text(
      attempt??"",
      style: const TextStyle(
          fontSize: 18, color: Colors.black, fontWeight: FontWeight.w600),
    );
  }

  Widget generateItemProfileBtn(BuildContext context,String? passing,int? useless) {
    return Container(
      decoration: const BoxDecoration(
        borderRadius: BorderRadius.all(Radius.circular(4)),
        color: Colors.black,
      ),
      padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 9),
      child: Text(
        passing??"",
        style: const TextStyle(
            color: Colors.white, fontSize: 14, fontWeight: FontWeight.bold),
      ),
    );
  }

  Widget generateItemMoney(String? wheel) {
    return Text(
      wheel??"",
      style: const TextStyle(
          fontSize: 24, color: Color(0xFFFF8800), fontWeight: FontWeight.w900),
      maxLines: 1,
      overflow: TextOverflow.ellipsis,
      textAlign: TextAlign.start,
    );
  }

  Widget generateItemTip(String? requested) {
    return AutoSizeText(requested??"",
        maxFontSize: 12,
        minFontSize: 5,
        maxLines: 1,
        style: const TextStyle(
            fontSize: 12,
            color: Color(0xFF333333),
            fontWeight: FontWeight.w600),
        textAlign: TextAlign.start,
        overflow: TextOverflow.ellipsis,
    );
  }

  Widget generateItemBottomLeft(String? doors) {
    return Text(
      doors??"",
      style: const TextStyle(
          fontSize: 15, fontWeight: FontWeight.w600, color: Color(0xFF333333)),
    );
  }

  Widget generateItemBottomRight(String? steps) {
    return Text(
      steps??"",
      style: const TextStyle(
          fontSize: 15, fontWeight: FontWeight.w600, color: Color(0xFF333333)),
    );
  }

  void onRequestClickAccess() {
    FMProgressHud.showLoading();
    String useless = "";
    if(widget.topEntity != null){
      useless = widget.topEntity?.useless.toString()??"";
    }
    FMHomeClickAccessApi api = FMHomeClickAccessApi(useless: useless);


    api.send<FMHomeClickAccessEntity, FMHomeClickAccessEntity>(decodeType: FMHomeClickAccessEntity()).then((value) {
      FMProgressHud.hideLoading();
      if (value.code == -2) {
        FMRouteTool.push(FMGlobalManager().context!, const FMLoginPage());
        return;
      }
      if(value.data == null){
        FMToast.showText(value.message ?? "Network request error");
        return;
      }
      FMJumpTool.jumpWidget(url: value.data?.bidding ?? "");
    });
  }

  void authCompleted(String bidding){
    FMJumpTool.jumpWidget(url: bidding);
    // showDialog(
    //     context: context,
    //     builder: (context) {
    //       return FMAuthCompletedDialog(
    //         onConfirm: () {
    //           Navigator.of(context).pop();
    //           FMJumpTool.jumpWebWidget(context: this.context, url: bidding);
    //         },
    //       );
    //     });
  }

  double offsetTop(BuildContext context) {
    return MediaQuery.of(context).viewPadding.top;
  }

  @override
  void onLocationError(String error) {
    // TODO: implement onLocationError
  }

  @override
  void onLocationUpdated(Position position) {
    controller.position = position;
  }
}
